package com.hluobo.gnnulibrary.ui;

import java.lang.ref.WeakReference;
import java.net.SocketTimeoutException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.hluobo.gnnulibrary.R;
import com.hluobo.gnnulibrary.R.anim;
import com.hluobo.gnnulibrary.R.id;
import com.hluobo.gnnulibrary.R.layout;
import com.hluobo.gnnulibrary.R.string;
import com.hluobo.gnnulibrary.engine.SplashService;
import com.hluobo.gnnulibrary.model.UpdateInfo;

public class SplashActivity extends Activity {

	private static final long SPLASH_DELAYMILLIS = 1500;
	private static final String MY_PREFERENCES = "preferences";
	private static final String TAG = "com.hluobo.gnnulibrary";

	private SharedPreferences preferences = null;
	private SplashService service = null;
	private UpdateInfo updateInfo = null;

	private MHandler handler = new MHandler(this);

	static class MHandler extends Handler {
		WeakReference<SplashActivity> outerClass;

		MHandler(SplashActivity activity) {
			outerClass = new WeakReference<SplashActivity>(activity);
		}

		@Override
		public void handleMessage(android.os.Message msg) {
			SplashActivity theClass = outerClass.get();
			switch (msg.what) {
			case 0: {
				// 使用theClass访问外部类成员和方法
				theClass.showUpgradeDialog(msg.obj.toString());
				break;
			}
			default: {
				Log.w(TAG, "未知的Handler Message:" + msg.what);
			}
			}

		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		
		// 显示当前版本号
		TextView versionText = (TextView) this.findViewById(R.id.splash_tv_version);
		versionText.setText("V "+getApplicationVersionName());

		preferences = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);

		if (networkActive()) {

			// 是否允许检测更新
			boolean allowCheckUpdate = preferences.getBoolean(
					"allowCheckUpdate", true);
			if (allowCheckUpdate) {
				// 检查更新
				String serverPath = getResources().getString(
						R.string.serverPath);
				Log.i(TAG, "更新服务器地址：" + serverPath);
				new CheckUpdateTask(serverPath).start();

			} else {

				Log.i(TAG, "自动检测更新关闭");
				
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						loadMainActivity();
					}
				}, SPLASH_DELAYMILLIS);
				
			}
		} else {
			// TODO 网络连接失败 对话框提示设置网络还是离线访问
			
			//loadMainActivity();
			
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					loadMainActivity();
				}
			}, SPLASH_DELAYMILLIS);
			
			Log.w(TAG, "无网络连接…");
			Toast.makeText(getApplicationContext(), "无网络连接…", Toast.LENGTH_LONG)
					.show();
		}

	}

	/**
	 * 检查当前是否有网络可用
	 * 
	 * @return
	 */
	private boolean networkActive() {

		ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = manager.getActiveNetworkInfo();
		if (networkInfo != null) {
			Log.i(TAG, "当前有可用网络！");
			return true;
		}
		return false;
	}

	/**
	 * 检查更新任务
	 * 
	 */
	class CheckUpdateTask extends Thread {

		private String serverPath;

		public CheckUpdateTask(String serverPath) {
			this.serverPath = serverPath;
		}

		@Override
		public void run() {

			try {
				sleep(SPLASH_DELAYMILLIS);

				service = new SplashService();
				// UpdateInfo info = service.getUpdateInfo(serverPath);
				updateInfo = service.getUpdateInfo(serverPath);
				int version = updateInfo.getVersion();
				if (version > getApplicationVersion()) {
					// 更新
					Log.i(TAG, "有新版本，提示用户是否需要更新……");

					// showUpgradeDialog(info.getDescription());
					// 子线程不可以处理UI
					Message msg = new Message();
					msg.what = 0;
					msg.obj = updateInfo.getDescription();
					handler.sendMessage(msg);

				} else {
					Log.i(TAG, "最新版本，无需更新。");
					loadMainActivity();
				}

				// loadNextScreen();

			} catch (SocketTimeoutException ste) {
				Log.e(TAG, "网络链接超时…");
				loadMainActivity();
			} catch (Exception e) {
				e.printStackTrace();
				loadMainActivity();
			} 
		}

	}

	/**
	 * 更新提示框
	 */
	private void showUpgradeDialog(String message) {
		// 显示更新提示框
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.splash_upgradedialog_title)
				.setMessage(message)
				.setPositiveButton("更新", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.i(TAG, "用户选择更新Application 版本");
						// 更新软件
						applicationUpgrade();
						loadMainActivity();
					}
				})
				.setNegativeButton("稍后", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.i(TAG, "用户取消更新");
					}
				});
		builder.create().show();
	}

	private void applicationUpgrade() {

		// 下载安装新版Application

		String url = updateInfo.getUrl();
		Log.i(TAG, "下载地址：" + url);
		String filename = parseNameFromURL(url);
		DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
		Request request = new Request(Uri.parse(url));
		request.setAllowedNetworkTypes(
				Request.NETWORK_MOBILE | Request.NETWORK_WIFI)
				.setAllowedOverRoaming(false)
				.setNotificationVisibility(0)
				.setDestinationInExternalPublicDir(
						Environment.DIRECTORY_DOWNLOADS, filename)
				.allowScanningByMediaScanner();

		manager.enqueue(request);

		Editor editor = preferences.edit();
		editor.putString(
				"appURI",
				Environment.getExternalStoragePublicDirectory(
						Environment.DIRECTORY_DOWNLOADS).getPath()
						+ filename);
		editor.commit();

	}

	private String parseNameFromURL(String url) {
		return url.substring(url.lastIndexOf("/"));
	}

	/**
	 * 载入主界面
	 */
	private void loadMainActivity() {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.splash_in, R.anim.splash_out);
		this.finish();
	}

	/**
	 * 获取当前App的版本号
	 * 
	 * @return 当前App的版本号
	 */
	private int getApplicationVersion() {

		PackageManager manager = getPackageManager();
		try {
			PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
			return info.versionCode;

		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		return -1;
	}
	
	/**
	 * 获取当前版本信息
	 * @return
	 */
	private String getApplicationVersionName() {

		PackageManager manager = getPackageManager();
		try {
			PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
			return info.versionName;

		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		return null;
	}

}
